import type { PDFDocumentProxy } from 'pdfjs-dist';
export interface IImg {
  src: string;
  width: number;
  height: number;
}

// 图片合并
export const combineImgs = (imgList: IImg[]): Promise<string> => {
  return new Promise((resolve, reject) => {
    let canvas = document.getElementById('canvas_combine_img') as HTMLCanvasElement;
    if (!canvas) {
      canvas = document.createElement('canvas'); //不需要append到dom中
      canvas.id = 'canvas_combine_img';
    }
    const canvasWidth = imgList.map((item) => item.width).sort((a, b) => a - b)[0];
    const canvasHeight = imgList.map((item) => item.height).reduce((prev, curr, index, array) => prev + curr, 0);
    canvas.width = canvasWidth;
    canvas.height = canvasHeight;
    const context = canvas.getContext('2d')!;
    function recursionDrawImage(imgTop: number, flag: number) {
      if (flag >= imgList.length) {
        resolve(canvas.toDataURL('image/jpeg'));
      } else {
        const img = new Image();
        const { src, width, height } = imgList[flag];
        img.crossOrigin = 'Anonymous'; //解决跨域问题
        img.src = src;
        img.onload = () => {
          context.drawImage(img, 0, imgTop, width, height); // 起始点：0, imgTop,
          imgTop += height;
          flag += 1;
          recursionDrawImage(imgTop, flag);
        };
      }
    }

    recursionDrawImage(0, 0);
  });
};

//window.URL.createObjectURL(file) 根据文件返回文件bold的对象，该对象包含file的完整信息
// base64 转 Blob
export const convertBase64UrlToBlob = (urlData: string) => {
  const bytes = window.atob(urlData.split(',')[1]);
  //去掉url的头，并转换为byte
  //处理异常,将ascii码小于0的转换为大于0
  const ab = new ArrayBuffer(bytes.length);
  const ia = new Uint8Array(ab);
  for (let i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i);
  }
  return new Blob([ab], { type: 'image/jpeg' });
};

// pdf转成imgs
export const pdfTransformToImgs = (pdf: PDFDocumentProxy, maxPageNum: number): Promise<IImg[]> => {
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('2d');
  return new Promise((resolve, reject) => {
    let pdfPageNum = 1;
    const imgBase64Arrays: IImg[] = [];
    function pageItemToImg() {
      if (pdfPageNum > pdf._pdfInfo.numPages) {
        resolve(imgBase64Arrays);
      } else {
        // 获取pdf页
        pdf.getPage(pdfPageNum).then((page) => {
          // 获取页的尺寸
          const viewport = page.getViewport({ scale: 1 });
          // 设置canvas的尺寸
          canvas.width = viewport.width;
          canvas.height = viewport.height;
          // 将pdf页渲染到canvas上
          page.render({ canvasContext: context!, viewport: viewport }).promise.then(() => {
            const imgBase64 = canvas.toDataURL('image/jpeg');
            imgBase64Arrays.push({ src: imgBase64, width: viewport.width, height: viewport.height });
            pdfPageNum++;
            pageItemToImg();
          });
        });
      }
    }
    if (maxPageNum && pdf._pdfInfo.numPages > maxPageNum) {
      reject('最多只能上传35页');
      return;
    }

    pageItemToImg();
  });
};
